package online_store.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import online_store.model.bus.UserBus;
import online_store.model.dto.UserDTO;

public class RegisterServlet extends HttpServlet{
	
	private UserBus userBus;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		userBus = new UserBus();
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("servlettttttttttttttttttttttttttttttttttttttttttttttttttttttttttt");
		
		UserDTO user = new UserDTO();
		user.setUsername(request.getParameter("usernamesignup"));
		user.setPassword(request.getParameter("passwordsignup"));
		user.setEmail(request.getParameter("emailsignup"));
		
		String errorMessage = "";
		int rs = userBus.createUser(user);
		if(rs == -1){
			errorMessage = "?regiterErrorMessage=duplicated-username";
		}
		
		if(errorMessage.equals("")){
			HttpSession session = request.getSession();
			session.setAttribute("user_id", user.getId());
			session.setAttribute("username", user.getUsername());
			
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}else{
			response.sendRedirect("login.jsp" + errorMessage + "#toregister");
		}
	}
}
